package net.qhzw.vip.qiyu.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.enums.ApiErrorCode;
import com.baomidou.mybatisplus.extension.exceptions.ApiException;
import feign.FeignException;
import lombok.extern.slf4j.Slf4j;
import net.qhzw.vip.qiyu.feign.OAuth2FeignClient;
import net.qhzw.vip.qiyu.handler.MyException;
import net.qhzw.vip.qiyu.model.LoginResult;
import net.qhzw.vip.qiyu.util.JwtToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class OauthLoginService {

    @Autowired
    private OAuth2FeignClient oAuth2FeignClient;

    @Value("${basic.token:Basic Y29pbi1hcGk6Y29pbi1zZWNyZXQ=}")
    private String basicToken;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /***
     * 后台管理人员登录
     * @param username
     * @param password
     * @param loginType
     * @return
     */
    public LoginResult login(String username, String password, String loginType) {
        log.info("用户{}开始登录", username);
        try {
            ResponseEntity<JwtToken> tokenResponseEntity = oAuth2FeignClient.getToken("password", username, password, loginType, basicToken);
            if (tokenResponseEntity.getStatusCode() != HttpStatus.OK) {
                throw new ApiException(ApiErrorCode.FAILED);
            }
            JwtToken jwtToken = tokenResponseEntity.getBody();
            log.info("远程调用授权服务器成功,获取的token为{}", JSON.toJSONString(jwtToken, true));
            String token = jwtToken.getAccessToken();
            redisTemplate.opsForValue().set(token, "", jwtToken.getExpiresIn(), TimeUnit.SECONDS);
            return new LoginResult(jwtToken.getTokenType() + " " + token);
        } catch (FeignException e) {
            throw new MyException(400, "用户名或密码错误");
        }

    }
}
